<!--
 * @Description: 视频上传组件
 * @Author: liyujie
 * @Date: 2021/02/07
 * @Last Modified by: liyujie
 * @Last Modified time: 2021/02/07
-->
<template>
    <section class="video-upload-wrapper">
        <div
            class="video uploader-customer"
            style="margin-top: 12px"
            v-if="video_url || isUpload"
        >
            <!--上传完成显示-->
            <img
                :src="video_cover"
                v-if="video_cover"
                class="video-cover"
            >
            <!--播放和删除-->
            <div class="img-action">
                <i
                    class="el-icon-video-play"
                    @click="previewVideo()"
                />
                <i
                    class="el-icon-delete"
                    @click="handleDeleteVideo()"
                    v-if="!disabled"
                />
            </div>
            <!--上传中进度-->
            <div
                class="progress"
                v-show="isUpload"
            >
                <el-progress
                    :percentage="process"
                    :show-text="false"
                    color="#fff"
                />
            </div>
        </div>
        <el-upload
            class="upload-demo"
            style="margin-top: 12px"
            action="noAction"
            ref="uploadVideo"
            accept="video/MP4,video/ogg,video/mkv,video/avi,video/rmvb,.mov,.flv,.mpg"
            :show-file-list="false"
            :http-request="handleUploadVideo"
            :before-upload="beforeUploadVideo"
            v-show="!video_url && !isUpload"
            :disabled="disabled"
        >
            <div class="uploader-customer pic-item">
                <i :class="icon"/>
                <div class="upload-text">{{ text }}</div>
            </div>
        </el-upload>
        <p
            class="tips"
            style="margin-top: 16px"
        >
            {{ tips }}
        </p>
    </section>
</template>

<script>
import { videoPreviewDialog } from './video-preview';
export default {
    name: 'VideoUpload',
    props: {
        action: {
            type: String,
            required: true
        },
        requestPreview: {
            type: String,
            required: true
        },
        requestCover: {
            type: String,
            required: true
        },
        disabled: {
            type: Boolean,
            default: false
        },
        url: {
            type: String,
            default: ''
        },
        tips: {
            type: String,
            default: ''
        },
        limitType: {
            type: String,
            default: 'KB'
        },
        limit: {
            type: Number,
            default: 0
        },
        text: {
            type: String,
            default: '添加视频'
        },
        icon: {
            type: String,
            default: 'el-icon-video-camera'
        }
    },
    model: {
        prop: 'url',
        event: 'change'
    },
    computed: {
        video_url: {
            get() {
                return this.url;
            },
            set(val) {
                this.$emit('change', val);
            }
        }
    },
    data() {
        return {
            isUpload: false,
            process: 0,
            video_cover: '',
            // 预览路径
            preview_url: '',
        };
    },
    components: {},
    mounted(){},
    methods:{

        /**
         * 上传之前 大小限制
         * @param file
         * @returns {boolean}
         */
        beforeUploadVideo(file) {
            let isLt;

            if(this.limit === 0) {
                isLt = true;
            } else if(this.limitType === 'MB') {
                isLt = file.size / 1024 / 1024 < this.limit;
            } else {
                isLt = file.size / 1024 < this.limit;
            }

            if (!isLt) {
                this.$notify({
                    title: '提示',
                    message: `视频大小不能超过${this.limit}${this.limitType}`,
                    type: 'warning',
                    duration: 2000
                });
                return false;
            }

            return isLt;
        },

        /**
         * 上传视频
         * @param event
         */
        handleUploadVideo(event) {
            this.isUpload = true;
            this.getUploadAuth(event.file.name, event.file.size).then(res => {
                this.$emit('upload', this.isUpload);
                let video = new FormData();

                video.append('file', event.file);
                video.append('policy', res.body.policy);
                video.append('signature', res.body.signature);

                this.$upload({
                    url: res.api,
                    data: video,
                    progress: (e) => {
                        setTimeout(() => {
                            this.process = Number(e.percent);
                        }, 0);
                        // console.log('当前上传进度:' + Number(e.percent.toFixed(1) * 1));
                    },
                    success: async resp => {
                        if (resp.code === 200) {
                            this.video_url = resp.url;
                            this.preview_url = await this.getPreviewUrl(resp.url);
                            this.isUpload = false;
                            this.video_cover = await this.getUploadCover(resp.url);
                            this.$emit('after-upload', {
                                video_cover: this.video_cover,
                                video_url: this.video_url,
                                preview_url: this.preview_url
                            });
                        } else {
                            //上传失败
                            this.$notify({
                                title: '提示',
                                message: resp.message,
                                type: 'warning',
                                duration: 2000
                            });
                        }

                        this.$refs.uploadVideo.clearFiles();
                        this.process = 0;
                    },
                    fail: error => {
                        this.$refs.uploadVideo.clearFiles();
                        this.isUpload = false;
                        this.$notify({
                            title: '提示',
                            message: '上传视频失败',
                            type: 'warning',
                            duration: 2000
                        });
                    }
                });
            });
        },

        /**
         * 获取视频上传参数
         * @param file_name
         * @param file_size
         * @returns {Promise<unknown>}
         */
        getUploadAuth(file_name, file_size) {
            return new Promise((resolve, reject) => {
                this.$post(this.action, {
                    file_name,
                    file_size
                }, resp => {
                    if (resp.code === 1) {
                        resolve(resp.data);
                    } else {
                        this.$notify({
                            title: '提示',
                            message: resp.msg,
                            type: 'warning',
                            duration: 2000
                        });
                    }
                });
            });
        },

        /**
         * 获取视频封面
         * @param file_path
         * @param snap_time
         * @returns {Promise<unknown>}
         */
        getUploadCover(file_path, snap_time = 2) {
            return new Promise((resolve, reject) => {
                this.$post(this.requestCover, {
                    file_path,
                    snap_time
                }, resp => {
                    if (resp.code === 1) {
                        resolve(resp.data.image_url);
                    } else {
                        this.$notify({
                            title: '提示',
                            message: resp.msg,
                            type: 'warning',
                            duration: 2000
                        });
                    }
                });
            });
        },

        /**
         * 获取视频预览地址
         * @param path
         * @returns {Promise<unknown>}
         */
        getPreviewUrl(path) {
            return new Promise((resolve, reject) => {
                this.$post(this.requestPreview, {
                    path
                }, resp => {
                    if (resp.code === 1) {
                        resolve(resp.data.url);
                    } else {
                        this.$notify({
                            title: '提示',
                            message: resp.msg,
                            type: 'warning',
                            duration: 2000
                        });
                    }
                });
            });
        },

        /**
         * 预览视频
         */
        previewVideo() {
            videoPreviewDialog({previewUrl: this.preview_url});
        },

        /**
         * 删除视频
         */
        handleDeleteVideo() {
            this.isUpload = false;
            this.video_url = '';
            this.video_cover = '';
            this.preview_url = '';
            this.process = 0;
            this.$emit('after-upload', {
                video_cover: this.video_cover,
                video_url: this.video_url,
                preview_url: this.preview_url
            });
            this.$emit('upload', this.isUpload);
        },

        /**
         * 设置回显
         */
        async setData(video_url) {
            this.preview_url = await this.getPreviewUrl(video_url);
            this.video_cover = await this.getUploadCover(video_url);
        }
    }
};
</script>

<style scoped lang="less">
.video-upload-wrapper {
    .uploader-customer {
        width: 100px;
        height: 100px;
        display: flex;
        justify-content: center;
        align-items: center;
        flex-direction: column;
        color: #999;
        padding-top: 12px;
        position: relative;
        border-radius: 4px;
        overflow: hidden;
        border: 1px dashed #aaa;

        i {
            font-size: 20px;
        }

        .video-cover {
            width: 100px;
            height: 100px;
            position: absolute;
            left: 0;
            top: 0;
        }

        .img-action {
            position: absolute;
            left: 0;
            top: 0;
            z-index: 1;
            width: 100px;
            height: 100px;
            border-radius: 4px;
            background: rgba(0, 0, 0, .6);
            justify-content: center;
            align-items: center;
            display: none;

            i {
                color: #ffffff;
                font-size: 17px;
                cursor: pointer;
            }

            .el-icon-delete {
                margin-left: 17px;
            }
        }

        &:hover {
            .img-action {
                display: flex;
            }
        }

        .progress {
            padding: 12px;
            box-sizing: border-box;
            position: absolute;
            left: 0;
            top: 0;
            z-index: 1;
            width: 100px;
            height: 100px;
            border-radius: 4px;
            background: rgba(0, 0, 0, .6);

            /deep/ .el-progress {
                margin-top: 50%;
                transform: translateY(-50%);

                .el-progress-bar__outer {
                    background: rgba(255, 255, 255, .2);
                }
            }

        }
    }
}
</style>
